<template>
  <!-- 职务管理-添加 -->
  <div>
    <Form
      :model="modelForm"
      ref="jobForm"
      class="ivu-form-no-margin-bottom"
      :rules="rule"
      :label-width="80"
    >
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="code" :label="$t('module.job.jobCode')">
            <Input
              v-model.trim="modelForm.code"
              :placeholder="$t('module.job.warning.enterJobCode')"
              :disabled="jobId != ''"
              
            ></Input>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item prop="name" :label="$t('module.job.jobName')">
            <Input
              v-model.trim="modelForm.name"
              :maxlength="50"
              :placeholder="$t('module.job.warning.enterJobName')"
              
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="startDate" :label="$t('module.job.effectBegin')">
            <DatePicker
              type="date"
              ref="startDate"
              :placeholder="$t('module.job.selectDate')"
              :value="modelForm.startDate"
              @on-change="onStartDateChange"
              :options="startDateOptions"
              :transfer="true"
              :editable="false"
              :clearable="false"
              placement="bottom-end"
              style="width: 100%;"
              
            ></DatePicker>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item prop="endDate" :label="$t('module.job.effectEnd')">
            <DatePicker
              type="date"
              ref="endDate"
              :placeholder="$t('module.job.permanent')"
              :value="modelForm.endDate"
              @on-change="onEndDateChange"
              :options="endDateOptions"
              :transfer="true"
              :editable="false"
              :clearable="false"
              placement="bottom-end"
              style="width: 100%;"
              
            ></DatePicker>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="level" :label="$t('module.job.level')">
            <Input placeholder v-model="modelForm.level" :maxlength="32"  />
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item prop="enabled" :label="$t('common.status')">
            <RadioGroup v-model="modelForm.enabled" >
              <Radio :label="1">
                <span>{{ $t("common.enable") }}</span>
              </Radio>
              <Radio :label="0">
                <span>{{ $t("common.disable") }}</span>
              </Radio>
            </RadioGroup>
          </Form-item>
        </Col>
      </Row>
      <Form-item :label="$t('module.job.description')">
        <Input
          placeholder
          type="textarea"
          :rows="4"
          v-model="modelForm.jobDesc"
          :maxlength="100"
          
        />
      </Form-item>
    </Form>
    <FormCreate
      :templateId.sync="modelForm.attributeContext"
      templateType="JOB"
      :attributeValue="modelForm.attributeValue"
      :fApi.sync="fApi"
      :options="fcOption"
      isClearable
      :selectWidth="'358px'"
    />
  </div>
</template>
<script>
import jobAPI from "@/api/jobAPI.js";
import locales from "./locales.js";
import { codeReg } from "@/const.js";
import FormCreate from "@/components/common/FormCreate";
// 一天的毫秒数
const ONE_DAY = 86400000;

export default {
  name: "job-edit",
  mixins: [locales],
  components: {FormCreate},
  props: {
    tenantCode: {
      type: String,
      default() {
        return "";
      }
    },
    jobId: {
      type: String,
      default() {
        return "";
      }
    },
    detailData: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    const validateJobCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("module.job.warning.enterJobCode")));
      } else if (value.length > 30) {
        callback(new Error(this.$t("common.warning.codeCheckLength")));
      } else if (!new RegExp(codeReg).test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      } else if (new RegExp("[\u4e00-\u9fa5]").test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      }
      callback();
    };
    const validateDate = (rule, value, callback) => {
      if (this.validateOther) {
        this.validateOther = false;
      } else {
        this.validateOther = true;
        if (rule.field == "startDate") {
          this.$refs["jobForm"].validateField("endDate");
        } else {
          this.$refs["jobForm"].validateField("startDate");
        }
      }
      if (!this.modelForm.startDate || !this.modelForm.endDate) {
        callback();
        return;
      } else if (this.modelForm.startDate > this.modelForm.endDate) {
        callback(new Error(this.$t("module.job.warning.validateDate")));
      }
      callback();
    };
    return {
      fApi: null,
      validateOther: false,
      modelForm: {
        tenantCode: null,
        id: "",
        code: "",
        name: "",
        startDate: "",
        endDate: "",
        level: "",
        enabled: 1,
        jobDesc: "",
        attributeContext: '',
        attributeValue: {}
      },
      rule: {
        code: [{ validator: validateJobCode, trigger: "blur", required: true }],
        name: [
          {
            required: true,
            message: this.$t("module.job.warning.enterJobName"),
            trigger: "blur"
          }
        ],
        startDate: [{ required: true, type: "string", trigger: "change" }],
        endDate: [{ required: true, type: "string", trigger: "change" }]
      },
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.save();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ]
    };
  },
  computed: {
    startDateOptions() {
      let _this = arguments[0];
      return {
        disabledDate(date) {
          if (typeof _this.modelForm.endDate == "object") {
            // 日期是日期对象，如 new Date()
            return (
              date &&
              date.valueOf() < Date.now() - ONE_DAY &&
              date.valueOf() > _this.modelForm.endDate.valueOf() - ONE_DAY
            );
          } else if (typeof _this.modelForm.endDate == "string") {
            // 日期是日期字符串，如 2020-01-08
            // 转换日期格式
            let formatStr = _this.modelForm.endDate.replace(/-/g, "/");
            let endDate = new Date(formatStr);
            return date && (date.valueOf() < Date.now() - ONE_DAY || date.valueOf() > endDate.valueOf());
          }
          return date && date.valueOf() < Date.now() - ONE_DAY;
        }
      };
    },
    endDateOptions() {
      let _this = arguments[0];
      return {
        disabledDate(date) {
          if (typeof _this.modelForm.startDate == "object") {
            // 生效日期是日期对象，如 new Date()
            return date && date.valueOf() < _this.modelForm.startDate.valueOf() - ONE_DAY;
          } else if (typeof _this.modelForm.startDate == "string") {
            // 生效日期是日期字符串，如 2020-01-08
            // 转换日期格式
            let formatStr = _this.modelForm.startDate.replace(/-/g, "/");
            let startDate = new Date(formatStr);
            return date && date.valueOf() < startDate.valueOf();
          }
          return date && date.valueOf() < Date.now() - ONE_DAY;
        }
      };
    },
    fcOption() {
      return {
        global: {
          "*": {
            col: {
              span: 12
            },
            props: {
              width: "355px",
            }
          }
        },
        form: {
          labelWidth: 100,
          size: "default"
        }
      };
    }
  },
  created: function() {
    this.init();
    if (this.jobId) {
      this.$emit("SetTitle", this.$t("module.job.editJob"));
    } else {
      this.$emit("SetTitle", this.$t("module.job.createJob"));
    }
    this.$emit("SetPageWidth", 700);
    this.$emit("SetPageActions", this.actions);
  },
  mounted: function() {
    // this.init();
  },
  methods: {
    init() {
      if (this.jobId) {
        this.modelForm.tenantCode = this.detailData.tenantCode;
        this.modelForm.id = this.detailData.id;
        this.modelForm.code = this.detailData.code;
        this.modelForm.name = this.detailData.name;
        this.modelForm.level = this.detailData.level;
        this.modelForm.enabled = this.detailData.enabled;
        this.modelForm.jobDesc = this.detailData.jobDesc;
        this.modelForm.startDate = this.formatDateTime(this.detailData.startDate);
        this.modelForm.endDate = this.detailData.endDate == null ? "" : this.formatDateTime(this.detailData.endDate);
        this.modelForm.attributeContext = this.detailData.attributeContext;
        this.modelForm.attributeValue = this.detailData;
      } else {
        // 默认有效期
        this.modelForm.startDate = new Date()
          .toISOString()
          .replace(/T.*/, " ")
          .trim();
        this.modelForm.endDate = "2099-12-31";
        this.modelForm.tenantCode = this.tenantCode;
      }
    },
    // 补零
    addZero(num) {
      return num < 10 ? "0" + num : num;
    },
    // 格式化时间
    formatDateTime(date) {
      var time = new Date(Date.parse(date));
      time.setTime(time.setHours(time.getHours() + 8));
      var Y = time.getFullYear() + "-";
      var M = this.addZero(time.getMonth() + 1) + "-";
      var D = this.addZero(time.getDate()) + " ";
      var h = this.addZero(time.getHours()) + ":";
      var m = this.addZero(time.getMinutes()) + ":";
      var s = this.addZero(time.getSeconds());
      return Y + M + D;
    },

    save() {
      this.$refs["jobForm"].validate(valid => {
        if (valid) {
          if (this.fApi && this.fApi.formData) {
            this.fApi.validate(valid => {
              if (valid) {
                this.modelForm.attributeValue = this.fApi.formData();
                this.onSubmit()
              }
            });
          } else {
            this.onSubmit()
          }
          
        }
      });
    },
    onSubmit () {
      this.actions[0].loading = true;
      const newFormData = {};
      if (this?.fApi?.formData) {
        const formData = this.fApi.formData();
        const rules = this.fApi.rule;
        for (const r of rules) {
          newFormData[r.matchColumn] = r.type === 'checkbox'
            ? JSON.stringify(formData[r.field])
            : formData[r.field];
        }
      }
      const requestParams = {
        ...this.modelForm,
        ...newFormData
      };
          if (this.modelForm.id) {
            jobAPI
              .updateJob(requestParams)
              .then(response => {
                this.actions[0].loading = false;
                this.$message.success({
                  content: this.$t("module.job.warning.updateJobSuccessfully"),
                  duration: 3
                });
                this.$emit("Close", true);
              })
              .catch(data => {
                this.actions[0].loading = false;
              });
          } else {
            jobAPI
              .addJob(requestParams)
              .then(response => {
                this.actions[0].loading = false;
                this.$message.success({
                  content: this.$t("module.job.warning.createJobSuccessfully"),
                  duration: 3
                });
                this.$emit("Close", true);
              })
              .catch(data => {
                this.actions[0].loading = false;
              });
          }
    },
    onStartDateChange(date) {
      this.modelForm.startDate = date;
    },
    onEndDateChange(date) {
      this.modelForm.endDate = date;
    }
  }
};
</script>
